package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.vo.VideoInfoForm;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-02-10
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    //注入阿里云接口
    @Autowired
    private VodClient vodClient;

    @Override
    public Boolean UpdateVideoInfoFormById(VideoInfoForm videoInfoForm) {
        EduVideo eduVideo = new EduVideo();
        BeanUtils.copyProperties(videoInfoForm,eduVideo);

        int flag = baseMapper.updateById(eduVideo);
        return flag>0;
    }

    /**
     * 删除课程里面的小节
     * todo 当有视频时也要删除小节里面的视频
    **/
    @Override
    public void deleteVideoByCourseInfo(String courseId) {
        //根据课程id删除所有的视频
        QueryWrapper<EduVideo> videoQueryWrapper =new QueryWrapper<>();
        videoQueryWrapper.eq("course_id",courseId);
        //只选这列的video_source_id
        videoQueryWrapper.select("video_source_id");
        List<EduVideo> eduVideos = baseMapper.selectList(videoQueryWrapper);
        //新建传入删除阿里云的视频id集合
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < eduVideos.size(); i++) {
            String id = eduVideos.get(i).getVideoSourceId();
            if(!StringUtils.isEmpty(id)){
                arrayList.add(id);
            }

        }

        if(arrayList.size()>0){
            //删除视频
            vodClient.deleteAliyunVideoBatch(arrayList);
        }



        //删除小节
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }







}
